/**
 * 获取地址栏参数
 * @param {String} url
 * @returns {String}
 */
function location(url) {
    let parsed = {
        href: '',
        host: '',
        hostname: '',
        port: '',
        search: '',
        query: {}
    }
    let href = url ? url : location.href;
    // 检测href地址
    if (!href.match(/^[a-z0-9.+-]+:\/\//i)) return false
    // 获取协议、主机名、端口、路径、hash、参数
    parsed.path = href.replace(/^([a-z0-9.+-]*:)\/\//, function (text, protocol) {
        parsed.protocol = protocol
        return ''
    }).replace(/^([a-z0-9.+-]*)(:\d+)?\/?/, function (text, hostname, port) {
        let portText = port || ''
        parsed.port = portText.replace(':', '')
        parsed.hostname = hostname
        parsed.host = hostname + portText
        return '/'
    }).replace(/(#.*)/, function (text, hash) {
        parsed.hash = hash.length > 1 ? hash : ''
        return ''
    })
    // 获取参数
    let searchs = href.replace(/#.*/, '').match(/(\?.*)/)
    let paramsKey = searchs ? searchs[1].replace(/^\?/, '') : '';
    let query = paramsKey.split('&').map(function (item) {
        let key = item.split('=')[0]
        let value = item.split('=')[1]
        return {
            key,
            value
        }
    }).reduce(function (pre, cur) {
        pre[cur.key] = cur.value
        return pre
    }, {})

    parsed.href = href;
    parsed.search = searchs && searchs[1] && searchs[1].length > 1 ? searchs[1] : '';
    parsed.query = query;

    return parsed
}

module.exports = location